/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, { useEffect, useState,useRef } from 'react';
import { StatusBar, Text, TouchableOpacity, View ,Image, ScrollView, ImageBackground, Alert} from 'react-native';
import AsyncChildComponent from '../learn/AsyncChildComponent';
import AsyncStorage from '@react-native-async-storage/async-storage'; 
import styles from './DialogStyles';
import { NativeModules } from 'react-native';
import BottomSheet, { BottomSheetMethods } from '@devvie/bottom-sheet';
const {  WeChat } = NativeModules;
const AWARDLIST = [
    { id: '1', value: 'purchase_all' },
    { id: '2', value: 'purchase_oneup' },
    { id: '3', value: 'purchase_onedown' },
    { id: '4', value: 'purchase_twoup' },
    { id: '5', value: 'purchase_twodown' },
    { id: '6', value: 'purchase_threeup' },
    { id: '7', value: 'purchase_threedown' },
    { id: '8', value: 'purchase_fourup' },
  ];
const shareonWechat = async(index:Number)=>{
  WeChat.registerApp('wx89a522ad1639e6bd', '', (error, result) => {
    if (error) {
        console.error('注册失败:', error);
    } else {
        console.log('注册成功:', result);
    }
});
  const flag = await WeChat.isWXAppInstalled(()=>{}); //判断是否安装微信 
  console.log(flag); 
  // WeChat.shareText({
  //   text: 'https://mp.weixin.qq.com/s/12D-fzybA8YAWN-jGLg9Sg?from=singlemessage&scene=1&subscene=10000&clicktime=1733324261&enterid=1733324261',
  //   scene: 0,
  // },()=>{});
  const webdata = {
    webpageUrl: 'https://mp.weixin.qq.com/s/12D-fzybA8YAWN-jGLg9Sg?from=singlemessage&scene=1&subscene=10000&clicktime=1733324261&enterid=1733324261',
    title: '每天五分钟 一千五百汉字轻松学',
    description: '我获得了一艘飞船赶紧和我一起学习把！',
    thumbImageUrl: 'https://img-blog.csdnimg.cn/f69bc71dc1a64e0bab988980e7cd29c1.gif#pic_center',
    scene: index,
  };
  WeChat.shareWebpage( webdata,()=>{});
};
const Awardshop = ({route,navigation}) => { 
 const sheetRef = useRef<BottomSheetMethods>(null); 
 const handledisplay = () => {
    sheetRef.current?.open();
 }
  const [bought,setBought] = useState<{id:String}[]>([{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'}, {'id': '5'}, {'id': '6'}, {'id': '7'}, {'id': '8'}]);
    const dealwithbought = async (index:number) => {
      let m = await AsyncStorage.getItem('star');
console.log(m + 'awardsi=hp');
      if ( m === null ){
         await AsyncStorage.setItem('star', '300');
        m = await AsyncStorage.getItem('star');
      }
console.log(m + 'awardsi=hp');
        let n = Number(m);
        if (n >= 5){
          await AsyncStorage.setItem('star',`${n - 5}`);
          await AsyncStorage.setItem( `awardID_${index}`,'0');
          const boughtData = await initasync(); // 使用 await 等待结果
          setBought(boughtData); // 更新状态
          Alert.alert(
            '',
            '购买成功',
            [
              { text: '确定', onPress: () => console.log('Ask me later pressed')},

            ],
            { cancelable: false }
          );

        } else {
          Alert.alert(
            '',
            '星星不够，快去练习吧！',
            [
              { text: '确定', onPress: () => console.log('Ask me later pressed')},

            ],
            { cancelable: false }
          );
        }


    };
    const initasync = async () =>  {
        let res = [];
        if (await AsyncStorage.getItem('awardID_1') === null){
            for (
                let i = 0; i < AWARDLIST.length; i++) {
                // 为每个奖项创建一个唯一的键
                const key = `awardID_${i + 1}`;
                // 将 AWARDLIST 数组中每个奖项的 id 存储到 AsyncStorage
               AsyncStorage.setItem(key, AWARDLIST[i].id);
               let m = {id: String(i + 1)};
               res.push(m);
               console.log(m + '111111111111');
              }
        } else {
            for (
                let i = 0; i < AWARDLIST.length; i++) {
                // 为每个奖项创建一个唯一的键
                const key = `awardID_${i + 1}`;
                // 将 AWARDLIST 数组中每个奖项的 id 存储到 AsyncStorage
                let m = {id: String(await AsyncStorage.getItem(key ))};
                res.push(m);
                console.log(String(m) + 'sdfsdfsdfsdfsdfsd');
              }
        }
        console.log(res);
       return res;
    };

      useEffect(() => {
        const loadBoughtData = async () => {
          const boughtData = await initasync(); // 使用 await 等待结果
          setBought(boughtData); // 更新状态
          console.log('boughtData:', boughtData); // 打印 boughtData
          console.log(bought); // 此时 bought 状态已经被更新
      };

      loadBoughtData(); // 调用异步函数
    }, []); // 空依赖数组确保这个effect只在组件挂载后运行一次
    return (
        <View style={{ resizeMode: 'contain',
            width: '100%',
            flex: 1,
            justifyContent: 'flex-end',backgroundColor:'blue'}}>
 <StatusBar
          hidden={false}
          backgroundColor="black"
          barStyle={ 'light-content'}
        />
        <View style={{flexDirection:'row',width:'100%',backgroundColor:'black'}}>
                <TouchableOpacity style={{height:'80%', left:0}} onPress={()=>{ navigation.navigate('home');}}>
                    <Image source={require('../../src/image/UI/img.png')} />
                </TouchableOpacity>
                <View style={{color:'#f7c808',fontSize:35,margin:5,backgroundColor:'black',width:'50%'}}>
                    <Text style={{color:'#f7c808',fontSize:35,margin:5,  textAlign:'center'}}>奖励墙</Text>
                </View>


                <TouchableOpacity style={{height:'80%', right:0}} onPress={()=>{ Alert.alert(
            '',
            '每个飞船只许兑换一次哦',
            [
              { text: '确定', onPress: () => console.log('Ask me later pressed')},

            ],
            { cancelable: false }
          );}}>
                    <Image source={require('../../src/image/UI/ic_award_rule.png')} />
                </TouchableOpacity>
        </View>

        <ScrollView style={{ height: '80%', backgroundColor: 'white' }}>
  {AWARDLIST.map((item, index) => (
    // 我们使用三元运算符来检查index是否为奇数
    // 如果是奇数，则渲染包含两个奖项的View
    index % 2 === 0 ? (
      <View key={index} style={{ flexDirection: 'row', height: 300 }}>
        <View style={{ width: '50%', backgroundColor: 'black',justifyContent:'center',alignContent:'center' }}>
            <View style={{ width: '80%',height:'80%', backgroundColor: 'black',borderRadius: 30  }}>
                <ImageBackground
                    source={{ uri: `asset:/awardpic/award${Number(index + 1)}.png` }}
                    style={{ height: '100%', width: '100%', margin: '10%'}}
                >
                  <View  style={{ height: '20%', width: '100%', alignItems:'center',position:'absolute',bottom:20}}>
                    <View style={{flexDirection:'row',justifyContent:'center'}}>
                    <Image  style={{height:30,width:30}} source={require('../../src/image/UI/award_star.png')} />
                     <Text style={{textAlign:'center',color:'white',fontWeight:'bold',fontSize:25}}>X5</Text>
                    </View>
                         <TouchableOpacity style={{ height: '100%', width: '100%',  alignItems: 'center' }} onPress={()=>{if (bought[index].id === '0'){console.log('去炫耀！'); handledisplay();} else {dealwithbought(index + 1);  }}}>

                        { bought[index].id === '0' ? <Image source={{ uri:'asset:/awardpic/award_buys.png' }} style={{height:20,width:60,top:'10%'}} /> : <Image source={{ uri:'asset:/awardpic/award_buy.png' }} style={{height:20,width:60,top:'10%'}} />}
                      </TouchableOpacity>
                  </View>

                </ImageBackground>
            </View>
        </View>
        <View  key={index + 1} style={{ width: '50%', backgroundColor: 'black',justifyContent:'center',alignContent:'center' }}>
            <View style={{ width: '80%',height:'80%', backgroundColor: 'black',borderRadius: 30  }}>
            <ImageBackground
                    source={{ uri: `asset:/awardpic/award${Number(index + 2)}.png` }}
                    style={{ height: '100%', width: '100%', margin: '10%'}}
                >
                  <View  style={{ height: '20%', width: '100%', alignItems:'center',position:'absolute',bottom:20}}>
                    <View style={{flexDirection:'row',justifyContent:'center'}}>
                    <Image  style={{height:30,width:30}} source={require('../../src/image/UI/award_star.png')} />
                     <Text style={{textAlign:'center',color:'white',fontWeight:'bold',fontSize:25}}>X5</Text>
                    </View>
                         <TouchableOpacity style={{ height: '100%', width: '100%',  alignItems: 'center' }} onPress={()=>{if (bought[index + 1].id === '0'){console.log('去炫耀！');handledisplay();} else {dealwithbought(index + 2);  }}}>

                         {bought[index + 1].id === '0' ? <Image source={{ uri:'asset:/awardpic/award_buys.png' }} style={{height:20,width:60,top:'10%'}} /> : <Image source={{ uri:'asset:/awardpic/award_buy.png' }} style={{height:20,width:60,top:'10%'}} />}
                      </TouchableOpacity>
                  </View>

                </ImageBackground>
            </View>
        </View>
      </View>
    ) : null // 如果index是偶数，则不渲染任何内容
  ))}
</ScrollView>
<BottomSheet ref={sheetRef} height={'30%'}>
       <View style={{flexDirection:'row',alignSelf:'center'}}>
        <TouchableOpacity onPress={()=>shareonWechat(1)}>
        <Image source={{ uri:'asset:/icon/friendcircle.png' }} style={{height:60,width:60,top:'10%',resizeMode:'stretch',margin:10,borderRadius:10}} />  
        <Text style={{alignSelf:'center'}}>朋友圈</Text>
        </TouchableOpacity>
        <View style={{width:'20%'}}></View>
        <TouchableOpacity onPress={()=>shareonWechat(0)}>
        <Image source={{ uri:'asset:/icon/wechatchat.png' }} style={{height:60,width:60,top:'10%',resizeMode:'stretch',margin:10,borderRadius:10}} />  
        <Text style={{alignSelf:'center'}}>聊天栏</Text>
        </TouchableOpacity>
       </View>
      </BottomSheet>
        </View>

    );

};

export default Awardshop;
